<?php

namespace app\index\controller;

use app\common\model\User;
use app\common\validate\PasswordChangeValidate;
use app\common\validate\PasswordValidate;
use Overtrue\SendCloud\SendCloud;
use think\Controller;
use think\Request;

class Password extends Controller
{

    public function index()
    {
        return view();
    }

    public function handler(Request $request)
    {
        $data = $request->only(['email']);
        $validator = new PasswordValidate;
        if (! $validator->check($data)) {
            $this->error($validator->getError());
        }

        // 检测邮箱是否存在
        $email = $data['email'];
        $emailExists = User::where('email', $email)->find();
        if (! $emailExists) {
            $this->error('邮箱不存在');
        }
        $user = $emailExists;

        // 邮箱存在
        $data = [
            'timestamp' => time(),
            'user_id' => $user->id,
        ];

        $data['sign'] = sha1($data['timestamp'] . $data['user_id'] . $data['timestamp'] . $data['user_id'] . $user->password);

        $url = url1('index/password/showPasswordChangePage') . '?' . http_build_query($data);

        $sendCloud = new SendCloud('xiaoteng_test_Vhhe7l', '0QfZo2OwcI0QyMht');
        $sendResult = $sendCloud->post('/mail/send', [
            'from' => 'xiaoteng123@NF3h72ctiTZfGNtTJXyjlDp07YN6t5jy.sendcloud.org',
            'to' => $user->email,
            'subject' => '密码重置邮件，来自小滕的测试',
            'html' => '<a href="' . $url . '">' . $url. '</a>',
        ]);

        if (200 != $sendResult['statusCode']) {
            $this->error('邮件发送失败');
        }

        $this->success('邮件发送成功，请到邮箱检查');
    }

    public function showPasswordChangePage()
    {
        return view();
    }

    public function passwordChangeHandler(Request $request)
    {
        $data = $request->only([
            'timestamp', 'user_id', 'sign',
            'password', 'password_confirm',
        ]);
        $validator = new PasswordChangeValidate;
        if (! $validator->check($data)) {
            return $this->error($validator->getError());
        }

        $user = User::find($data['user_id']);
        if (! $user) {
            $this->error('用户不存在');
        }

        // 验证加密字符串
        $sign = sha1($data['timestamp'] . $data['user_id'] . $data['timestamp'] . $data['user_id'] . $user->password);
        if ($sign != $data['sign']) {
            $this->error('URL地址错误');
        }

        // 验证时间
        if ((time() - 3600) > $data['timestamp']) {
            $this->error('请重新发送密码重置邮件，当前链接已过期');
        }

        // 所有的验证都通过啦
        $user->password = $data['password'];
        $user->save();

        $this->success('密码修改成功', url1('index/login/index'));
    }

}
